package com.hongxun.budget.ui.fragment.sg;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.hongxun.budget.R;
import com.hongxun.budget.ui.activity.sg.AuxiliaryActivity;
import com.hongxun.budget.ui.dialog.ListDialog;
import com.hongxun.budget.ui.fragment.BaseFragment;
import com.hongxun.budget.utils.LocationUtils;
import com.hongxun.budget.utils.SPUtils;
import com.hongxun.budget.utils.SgDBUtils;
import com.hongxun.budget.utils.SgStrKey;
import com.hongxun.entity.sg.CYbgcCj;
import com.hongxun.greenentity.sg.CMiddleCheckEntity;
import com.hongxun.greenentity.sg.CStackPointEntity;
import com.hongxun.interfaces.ResponseListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 中间检查2级界面
 */
public class MiddleCheckMap extends BaseFragment implements Handler.Callback {
    @BindView(R.id.sgmap)
    MapView map;
    @BindView(R.id.tv1)
    TextView tv1;

    private AMap aMap;
    private List<CYbgcCj> datasMap = new ArrayList<>();
    private List<CMiddleCheckEntity> listAll = new ArrayList<>();
    private List<Marker> markerList = new ArrayList<>();
    private Handler handler = new Handler(this);
    private List<String> list = new ArrayList<>();

    @Override
    public int getLayoutId() {
        return R.layout.sg_fragment_middlecheck_map;
    }

    @Override
    public void setMapBundle(Bundle bundle) {
        map.onCreate(bundle);
    }

    @Override
    public void initView() {
        if (aMap == null) aMap = map.getMap();
        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                nextView(marker.getTitle());
                return true;
            }
        });
        for (String s : getResources().getStringArray(R.array.mcSp1)) {
            list.add(s);
        }
        String uuid = String.valueOf(SPUtils.get(context, SgStrKey.uuidxm, ""));
        Observable.just(uuid).subscribeOn(Schedulers.io()).map(new Func1<String, Boolean>() {
            @Override
            public Boolean call(String value) {
                listAll = SgDBUtils.getCMceListAll(value);
                return true;
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean b) {
                getLocalData(0);
            }
        });
    }

    private void nextView(String title) {
        for (CYbgcCj data : datasMap) {
            if (data.getNameOrCode().equals(title)) {
                SPUtils.put(context, SgStrKey.uuidjl, data.getUuid());
                startActivity(new Intent(context, AuxiliaryActivity.class)
                        .putExtra("tabName", SgStrKey.ybgcxxlb));
                break;
            }
        }
    }

    @Override
    public void success(int i, JSONObject obj) {
        switch (i) {
            case 999:
                LatLng location = new LatLng(obj.getDoubleValue("latitude"), obj.getDoubleValue("longitude"));
                CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(location, 19);
                aMap.moveCamera(cameraUpdate);
                break;
        }
    }

    @OnClick(R.id.tv1)
    public void onViewClicked() {
        new ListDialog<CStackPointEntity>()
                .setTitle("检查类别")
                .setDatas(list)
                .setListener(new ResponseListener() {
                    @Override
                    public void response(Object... data) {
                        getLocalData(list.indexOf(data[0]));
                    }
                }).show(getFragmentManager(), "");
    }

    private void setLocations() {
        ArrayList<MarkerOptions> options = new ArrayList<>();
        for (CYbgcCj record : datasMap) {
            LatLng location = new LatLng(record.getLat(), record.getLng());
            CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(location, 20);
            aMap.animateCamera(cameraUpdate);
            View pointView = LayoutInflater.from(context).inflate(R.layout.sg_view_map_point, null);
            ((ImageView) pointView.findViewById(R.id.iv1)).setImageResource(R.mipmap.icon_location);
            TextView tvTitle = pointView.findViewById(R.id.tv1);
            String title = "";
            if (record.getCountPitPole() != 0) {
                title = "电杆坑：(" + record.getCountPitPole() + ")";
            }
            if (record.getCountPitLx() != 0) {
                title = title + "\n拉线坑：(" + record.getCountPitLx() + ")";
            }
            if (record.getCountEarthed() != 0) {
                title = title + "\n接地体：(" + record.getCountEarthed() + ")";
            }
            if (record.getCountSbjc() != 0) {
                title = title + "\n设备基础：(" + record.getCountSbjc() + ")";
            }
            if (title.isEmpty()) {
                title = record.getNameOrCode();
            }
            tvTitle.setText(title);
            if (record.getTabName().equals("100")) {
                tvTitle.setTextColor(getResources().getColor(R.color.colorAccent));
            } else {
                tvTitle.setTextColor(getResources().getColor(R.color.colorPrimary));
            }
            MarkerOptions options1 = new MarkerOptions()
                    .position(location)
                    .anchor(0.5f, 0.5f)
                    .title(record.getNameOrCode())
                    .draggable(false)
                    .icon(BitmapDescriptorFactory.fromView(pointView));
            options.add(options1);
        }
        ArrayList<Marker> markerArrayList = aMap.addMarkers(options, true);
        markerList.addAll(markerArrayList);
    }

    @Override
    public boolean handleMessage(Message msg) {
        aMap.clear();
        for (Marker marker : markerList) {
            marker.remove();
        }
        markerList.clear();
        if (datasMap.isEmpty()) {
            setMyLocaltion();
        } else {
            setLocations();
        }
        return false;
    }

    private void setMyLocaltion() {
        new LocationUtils(context, context, 3, 0, this);
    }

    private void getLocalData(final int position) {
        tv1.setText(list.get(position));
        datasMap.clear();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (CMiddleCheckEntity entity : listAll) {
                    CYbgcCj ybgcjc = new CYbgcCj();
                    ybgcjc.setUuid(entity.getGuid());
                    ybgcjc.setNameOrCode(entity.getMCName());
                    ybgcjc.setTabName(entity.getMCMode());

                    ybgcjc.setLat(entity.getMCLatitude());
                    ybgcjc.setLng(entity.getMCLongitude());

                    ybgcjc.setCountPitPole(SgDBUtils.getCPolePitList(entity.getGuid()).size());
                    ybgcjc.setCountPitLx(SgDBUtils.getCLinePitList(entity.getGuid()).size());
                    ybgcjc.setCountEarthed(SgDBUtils.getCGroundList(entity.getGuid()).size());
                    ybgcjc.setCountSbjc(SgDBUtils.getCBasicsWorkList(entity.getGuid()).size());

                    if (position == 1 && entity.getMCMode().equals("100")) {
                        datasMap.add(ybgcjc);
                    } else if (position == 2 && entity.getMCMode().equals("200")) {
                        datasMap.add(ybgcjc);
                    } else if (position == 0) {//全部
                        datasMap.add(ybgcjc);
                    }
                }
                handler.sendEmptyMessage(2);
            }
        }).start();
    }

    @Override
    public void initDault() {
        getLocalData(0);
    }

    @Override
    public void onResume() {
        super.onResume();
        map.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        map.onPause();
    }

    @Override
    public void onDestroy() {
        if (map != null) map.onDestroy();
        super.onDestroy();
    }

}
